package com.example.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CompletableFuture;

@Service
public class TimeService {

    @Async("taskExecutor")
    public CompletableFuture<Void> printCurrentTimeEverySecond(int duration) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (int i = 0; i < duration; i++) {
            try {
                String currentTime = sdf.format(new Date());
                System.out.println("🕒 当前时间: " + currentTime + " | 线程: " + Thread.currentThread().getName());
                Thread.sleep(1000); // 暂停1秒
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            }
        }

        return CompletableFuture.completedFuture(null);
    }

    @Async("taskExecutor")
    public CompletableFuture<Void> countdownTimer(int seconds) {
        System.out.println("⏰ 开始倒计时: " + seconds + "秒");

        for (int i = seconds; i > 0; i--) {
            try {
                System.out.println("⏳ 剩余时间: " + i + "秒 | 线程: " + Thread.currentThread().getName());
                Thread.sleep(1000); // 暂停1秒
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            }
        }

        System.out.println("🎉 倒计时结束！");
        return CompletableFuture.completedFuture(null);
    }
}